﻿Imports Odyssee.WebControles
Imports OpenDelib.ServiceDeliberations

Public Class FicheAssemblee
    Inherits FicheDossierPage

    Private Class Elu
        Public Property Cle As Integer
        Public Property Qualite As String
        Public Property Nom As String
        Public Property Prenom As String
        Public Property Lie As Boolean
        Public ReadOnly Property NomComplet As String
            Get
                Return Nom & If(Prenom = "", "", " " & Prenom)
            End Get
        End Property
        Public Sub New(contact As ServiceContacts.Contact, lie As Boolean)
            Me.Cle = contact.Cle
            Me.Qualite = contact.Qualite
            Me.Nom = contact.Nom
            Me.Prenom = contact.Prenom
            Me.Lie = lie
        End Sub
    End Class

    Protected ReadOnly Property TypeActionAssemblee As String
        Get
            Return Tools.GetInstance().Parametre(TypeParametre.TypeAction, TypeDeliberation.Assemblee)
        End Get
    End Property
    Protected ReadOnly Property TypeLienInterDossierAssemblee As String
        Get
            Return Tools.GetInstance().Parametre(TypeParametre.TypeLienInterDossierAssemblee)
        End Get
    End Property
    Protected ReadOnly Property TypeContactElu As String
        Get
            Return Tools.GetInstance().Parametre(TypeParametre.TypeContactElu)
        End Get
    End Property
    Protected ReadOnly Property TypeRelationElu As String
        Get
            Return Tools.GetInstance().Parametre(TypeParametre.TypeRelationElu)
        End Get
    End Property
    Protected ReadOnly Property TypeEntrepriseLieu As String
        Get
            Return Tools.GetInstance().Parametre(TypeParametre.TypeEntrepriseLieu)
        End Get
    End Property
    Protected ReadOnly Property TypeRelationLieu As String
        Get
            Return Tools.GetInstance().Parametre(TypeParametre.TypeRelationLieu)
        End Get
    End Property

    Public Overrides ReadOnly Property Titre As String
        Get
            Return "Fiche assemblée"
        End Get
    End Property
    Protected Overrides ReadOnly Property TypeDelib As TypeDeliberation
        Get
            Return TypeDeliberation.Assemblee
        End Get
    End Property
    Protected Overrides ReadOnly Property LibelleEntite As String
        Get
            Return "assemblée"
        End Get
    End Property
    Protected Overrides ReadOnly Property LibelleFeminin As Boolean
        Get
            Return True
        End Get
    End Property
    Protected Overrides ReadOnly Property LibelleApostrophe As Boolean
        Get
            Return True
        End Get
    End Property
    Protected Overrides ReadOnly Property UtiliseDocuments As Boolean
        Get
            Return False
        End Get
    End Property
    Protected Overrides ReadOnly Property PopupPanel As JQPopupPanel
        Get
            Return Me.pnlAssemblee
        End Get
    End Property
    Protected Overrides ReadOnly Property BoutonActualiser As Button
        Get
            Return Me.btnActualiser
        End Get
    End Property
    Protected Overrides ReadOnly Property SeparateurActualiser As ToolBarSeparator
        Get
            Return Me.tbSep1
        End Get
    End Property
    Protected Overrides ReadOnly Property BoutonEnregistrer As Button
        Get
            Return Me.btnEnregister
        End Get
    End Property
    Protected Overrides ReadOnly Property SeparateurTraitements As ToolBarSeparator
        Get
            Return Me.tbSep2
        End Get
    End Property
    Protected Overrides ReadOnly Property BoutonTraitements As ToolBarTextImageMenuButton
        Get
            Return Me.btnTraitements
        End Get
    End Property


    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            SetFocus(Me.txtObjet)
        End If
    End Sub


    Private Sub btnEnvoiConvocations_Click(sender As Object, e As EventArgs)
        Using svc As New DeliberationsClient
            Dim params As New ParametresEnvoiConvocations
            params.Authentication = New AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Assemblee = CleEntite

            Try
                Dim results As OperationResult
                results = svc.EnvoyerConvocationsAssemblee(params)
                If results.OK Then
                    NotifySuccess("Opération effectuée avec succès.")
                Else
                    NotifyErreur(results.ErrorMessage)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub

    Protected Sub chkEluLie_CheckedChanged(sender As Object, e As EventArgs)
        Dim chk As CheckBox = CType(sender, CheckBox)
        Dim numeroContact As Integer = CInt(chk.Text)
        Dim estLie As Boolean = chk.Checked

        ' Création ou suppression du lien dossier / contact
        If estLie Then
            AjouterLienContact(numeroContact, Me.TypeRelationElu)
        Else
            SupprimerLienContact(numeroContact, Me.TypeRelationElu)
        End If
    End Sub

    Protected Sub chkCommissionLiee_CheckedChanged(sender As Object, e As EventArgs)
        Dim chk As CheckBox = CType(sender, CheckBox)
        Dim codeCommission As String = chk.Text
        Dim estLiee As Boolean = chk.Checked

        ' Création ou suppression du lien inter-dossier
        If estLiee Then
            AjouterLienDossier(codeCommission, Me.TypeLienInterDossierAssemblee, True, False)
        Else
            SupprimerLienDossier(codeCommission, Me.TypeLienInterDossierAssemblee, True, False)
        End If
    End Sub

    Protected Sub chkRapportLie_CheckedChanged(sender As Object, e As EventArgs)
        Dim chk As CheckBox = CType(sender, CheckBox)
        Dim codeRapport As String = chk.Text
        Dim estLiee As Boolean = chk.Checked

        ' Création ou suppression du lien inter-dossier
        If estLiee Then
            AjouterLienDossier(codeRapport, Me.TypeLienInterDossierAssemblee, True, False)
        Else
            SupprimerLienDossier(codeRapport, Me.TypeLienInterDossierAssemblee, True, False)
        End If
    End Sub


    Protected Overrides Sub InitialiserParametres()
        MyBase.InitialiserParametres()

        ' Chargement de la liste des états
        Me.cmbEtat.Items.Clear()
        Using svc As New ServiceParametre.ParametresClient
            Dim params As New ServiceParametre.ListeParametreParameters
            params.Authentication = New ServiceParametre.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.EntiteParametrage = 25
            params.Param1 = Me.TypeDossier

            Try
                Dim results As ServiceParametre.OIItemListResult = svc.ListeParametre(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de charger la liste des états d'une assemblée" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                Else
                    For Each item As ServiceParametre.OIItem In results.Liste
                        Me.cmbEtat.Items.Add(New ListItem(item.Libelle, item.Code))
                    Next
                    Me.cmbEtat.SelectedIndex = 0
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using

        ' Chargement de la liste des lieux
        Me.cmbLieu.Items.Clear()
        Using svc As New ServiceEntreprises.EntreprisesClient
            Dim params As New ServiceEntreprises.CriteresRechercheEntreprise
            params.Authentication = New ServiceEntreprises.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Type = Me.TypeEntrepriseLieu

            Try
                Dim results As ServiceEntreprises.ResultatRechercheEntreprise = svc.Recherche(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de charger la liste des lieux d'une assemblée" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                Else
                    Me.cmbLieu.Items.Add(New ListItem("", ""))
                    For Each item As ServiceEntreprises.Entreprise In results.Entreprises
                        Me.cmbLieu.Items.Add(New ListItem(item.Cle, item.Cle))
                    Next
                    Me.cmbLieu.SelectedIndex = 0
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub

    Protected Overrides Sub InitialiserPage()
        MyBase.InitialiserPage()

        Select Case Me.ModeFiche

            Case Tools.ModeFiche.Creation
                Me.divElus.Visible = False
                Me.divCommissions.Visible = False
                Me.divRapports.Visible = False

            Case Tools.ModeFiche.Modification
                ' Dossier
                Me.txtObjet.Text = Me.Entite.Identificateur
                Me.txtResume.Text = Me.Entite.Remarques
                Me.cmbEtat.SelectedValue = Me.Entite.Etat
                Me.txtCode.Text = Me.Entite.Code

                ' Lieu de l'assemblée
                Using svc As New ServiceEntreprises.EntreprisesClient
                    Dim params As New ServiceEntreprises.CriteresRechercheEntreprise
                    params.Authentication = New ServiceEntreprises.AuthenticationParameters
                    params.Authentication.Token = Tools.GetInstance.getToken
                    params.Type = Me.TypeEntrepriseLieu
                    params.DossierLie = Me.CleEntite
                    params.TypeRelationDossierLie = Me.TypeRelationLieu

                    Try
                        Dim results As ServiceEntreprises.ResultatRechercheEntreprise = svc.Recherche(params)
                        If results Is Nothing OrElse Not results.OK Then
                            NotifyErreur("Impossible de charger le lieu lié à l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                        ElseIf results.Entreprises.Count > 0 Then
                            Me.cmbLieu.SelectedValue = results.Entreprises(0).Cle
                        End If
                    Catch ex As Exception
                        NotifyErreur(ex.Message)
                    End Try
                End Using

                ' Date de l'assemblée
                Dim action As ServiceActions.Action = LireActionDate()
                If action IsNot Nothing Then
                    Me.dteDateAssemblee.Date = If(action.Effectuee, action.EffectueeLe, action.AEffectuerLe)
                    Me.tmeHeure.Time = If(action.Effectuee, action.EffectueeHeureDebut, action.AEffectuerHeureDebut)
                End If

                ' Elus
                InitialiserLiensContacts()

                ' Commissions et rapports
                InitialiserLiensDossiers()

        End Select
    End Sub

    Protected Overrides Function Renseigner() As Boolean
        If Not MyBase.Renseigner() Then Return False
        Entite.Identificateur = Me.txtObjet.Text
        Entite.Remarques = Me.txtResume.Text
        Entite.Etat = Me.cmbEtat.SelectedValue
        Return True
    End Function

    Protected Overrides Function Creer() As Boolean
        Dim cleAction As Integer = 0

        If Not MyBase.Creer() Then Return False

        ' Création de la date
        If Not CreerActionDate(cleAction) Then Return False

        ' Ajout du lieu et de la date
        If Me.cmbLieu.SelectedValue <> "" Then
            Using svc As New ServiceDossiers.DossiersClient
                Dim pLieu As New ServiceDossiers.ParametresLienDossierEntrepriseContact
                pLieu.Authentication = New ServiceDossiers.AuthenticationParameters
                pLieu.Authentication.Token = Tools.GetInstance.getToken
                pLieu.CodeDossier = CleEntite
                pLieu.CleEntreprise = Me.cmbLieu.SelectedValue
                pLieu.TypeRelation = Me.TypeRelationLieu

                Try
                    Dim results As ServiceDossiers.OperationResult = svc.AjouterLienActeur(pLieu)
                    If results Is Nothing OrElse Not results.OK Then
                        NotifyErreur("Impossible de créer le lien entre le lieu '" & Me.cmbLieu.SelectedValue & "' et l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                        Return False
                    End If
                Catch ex As Exception
                    NotifyErreur(ex.Message)
                    Return False
                End Try

                If Not CreerLienActionDate(cleAction, svc) Then Return False
            End Using
        End If

        Return True
    End Function

    Protected Overrides Function MettreAJour() As Boolean
        If Not MyBase.MettreAJour() Then Return False

        ' Mise à jour du lieu
        If Not MettreAJourLieu() Then Return False

        ' Mise à jour de la commission
        If Not MettreAJourActionDate() Then Return False

        Return True
    End Function

    Protected Overrides Sub InitialiserBoutonsTraitement()
        MyBase.InitialiserBoutonsTraitement()

        ' Ajout d'un bouton pour l'envoi des convocations
        Me.SeparateurTraitements.Visible = True
        Me.BoutonTraitements.Visible = True

        Dim btn As New Odyssee.WebControles.ToolBarButton()
        btn.ID = "btnEnvoiConvocations"
        btn.OnClientClick = "return confirm('Êtes-vous sûr de vouloir exécuter cette action ?');"
        btn.Text = "Envoyer les convocations"
        AddHandler btn.Click, AddressOf btnEnvoiConvocations_Click
        Me.BoutonTraitements.Add(btn)
    End Sub



    Private Sub InitialiserLiensDossiers(Optional commissions As Boolean = True, Optional rapports As Boolean = True)
        If Not commissions And Not rapports Then Return

        Using svc As New DeliberationsClient
            Dim params As New ParametresListe
            params.Authentication = New AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken

            If commissions Then
                Try
                    Dim results As ResultatListeDossiersDeliberationOfCommissionwn7zOZhO = Nothing
                    results = svc.ListeCommissions(params)
                    If results Is Nothing OrElse Not results.OK Then
                        NotifyErreur("Impossible de charger les commissions de l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                    Else
                        results.Dossiers.Sort(Function(elementA As Commission, elementB As Commission)
                                                  If elementA.AssembleesLiees.Contains(Me.CleEntite) = elementB.AssembleesLiees.Contains(Me.CleEntite) Then
                                                      If IsNumeric(elementA.CodeDossier) And IsNumeric(elementB.CodeDossier) Then
                                                          Return CInt(elementA.CodeDossier).CompareTo(CInt(elementB.CodeDossier))
                                                      Else
                                                          Return elementA.CodeDossier.CompareTo(elementB.CodeDossier)
                                                      End If
                                                  ElseIf elementA.AssembleesLiees.Contains(Me.CleEntite) Then
                                                      Return -1
                                                  ElseIf elementB.AssembleesLiees.Contains(Me.CleEntite) Then
                                                      Return 1
                                                  End If
                                                  Return 0
                                              End Function)
                        Me.gvCommissions.DataSource = results.Dossiers
                        Me.gvCommissions.DataBind()
                        Me.gvCommissions.PageIndex = 0
                    End If
                Catch ex As Exception
                    NotifyErreur(ex.Message)
                End Try
            End If

            If rapports Then
                Try
                    Dim results As ResultatListeDossiersDeliberationOfRapportwn7zOZhO = Nothing
                    results = svc.ListeRapports(params)
                    If results Is Nothing OrElse Not results.OK Then
                        NotifyErreur("Impossible de charger les rapports de l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                    Else
                        For i As Integer = results.Dossiers.Count - 1 To 0 Step -1
                            If results.Dossiers(i).AssembleeLiee <> "" AndAlso results.Dossiers(i).AssembleeLiee <> Me.CleEntite Then results.Dossiers.RemoveAt(i)
                        Next
                        results.Dossiers.Sort(Function(elementA As Rapport, elementB As Rapport)
                                                  If elementA.AssembleeLiee = elementB.AssembleeLiee Then
                                                      If IsNumeric(elementA.CodeDossier) And IsNumeric(elementB.CodeDossier) Then
                                                          Return CInt(elementA.CodeDossier).CompareTo(CInt(elementB.CodeDossier))
                                                      Else
                                                          Return elementA.CodeDossier.CompareTo(elementB.CodeDossier)
                                                      End If
                                                  ElseIf elementA.AssembleeLiee <> "" Then
                                                      Return -1
                                                  ElseIf elementB.AssembleeLiee <> "" Then
                                                      Return 1
                                                  End If
                                                  Return 0
                                              End Function)
                        Me.gvRapports.DataSource = results.Dossiers
                        Me.gvRapports.DataBind()
                        Me.gvRapports.PageIndex = 0
                    End If
                Catch ex As Exception
                    NotifyErreur(ex.Message)
                End Try
            End If
        End Using
    End Sub
    Private Sub AjouterLienDossier(codeDossier As String, typeInterDossier As String, commissions As Boolean, rapports As Boolean)
        Using svc As New ServiceDossiers.DossiersClient
            Dim params As New ServiceDossiers.ParametresLienDossierDossier
            params.Authentication = New ServiceDossiers.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.CodeDossier = codeDossier
            params.CodeDossierLie = Me.CleEntite
            params.TypeRelation = typeInterDossier

            Try
                Dim results As ServiceDossiers.OperationResult
                results = svc.AjouterLienDossier(params)
                If results.OK Then
                    NotifySuccess("Ajout effectué avec succès.")
                    InitialiserLiensDossiers(commissions, rapports)
                Else
                    NotifyErreur(results.ErrorMessage)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub
    Protected Sub SupprimerLienDossier(codeDossier As String, typeInterDossier As String, commissions As Boolean, rapports As Boolean)
        Using svc As New ServiceDossiers.DossiersClient
            Dim params As New ServiceDossiers.ParametresLienDossierDossier
            params.Authentication = New ServiceDossiers.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.CodeDossier = codeDossier
            params.CodeDossierLie = Me.CleEntite
            params.TypeRelation = typeInterDossier

            Try
                Dim results As ServiceDossiers.OperationResult
                results = svc.SupprimerLienDossier(params)
                If results.OK Then
                    NotifySuccess("Suppression effectuée avec succès.")
                    InitialiserLiensDossiers(commissions, rapports)
                Else
                    NotifyErreur(results.ErrorMessage)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub

    Private Sub InitialiserLiensContacts()
        Dim contacts As List(Of ServiceContacts.Contact) = Nothing
        Dim contactsLies As List(Of ServiceContacts.Contact) = Nothing

        Using svc As New ServiceContacts.ContactsClient
            Dim params As New ServiceContacts.CriteresRechercheContact
            params.Authentication = New ServiceContacts.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Type = TypeContactElu

            ' Lecture de la liste complète des élus
            Try
                Dim results As ServiceContacts.ResultatRechercheContact = Nothing
                results = svc.Recherche(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de charger la liste des élus" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                Else
                    contacts = results.Contacts
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try

            ' Lecture de la liste des élus liés à l'assemblée
            params.DossierLie = Me.CleEntite
            params.TypeRelationDossierLie = Me.TypeRelationElu
            Try
                Dim results As ServiceContacts.ResultatRechercheContact = Nothing
                results = svc.Recherche(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de charger les élus de l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                Else
                    contactsLies = results.Contacts
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using

        ' Affectation de la liste des élus
        Dim elus As New List(Of Elu)
        If contacts IsNot Nothing Then
            For Each c As ServiceContacts.Contact In contacts
                elus.Add(New Elu(c, If(contactsLies Is Nothing, False, contactsLies.Exists(Function(x) x.Cle = c.Cle))))
            Next
        End If
        elus.Sort(Function(elementA As Elu, elementB As Elu)
                      If elementA.Lie = elementB.Lie Then
                          Return elementA.NomComplet.CompareTo(elementB.NomComplet)
                      ElseIf elementA.Lie Then
                          Return -1
                      ElseIf elementB.Lie Then
                          Return 1
                      End If
                      Return 0
                  End Function)
        Me.gvElus.DataSource = elus
        Me.gvElus.DataBind()
        Me.gvElus.PageIndex = 0
    End Sub
    Private Sub AjouterLienContact(cleContact As Integer, typeRelation As String)
        Using svc As New ServiceDossiers.DossiersClient
            Dim params As New ServiceDossiers.ParametresLienDossierEntrepriseContact
            params.Authentication = New ServiceDossiers.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.CleContact = cleContact
            params.CodeDossier = Me.CleEntite
            params.TypeRelation = typeRelation

            Try
                Dim results As ServiceDossiers.OperationResult
                results = svc.AjouterLienActeur(params)
                If results.OK Then
                    NotifySuccess("Ajout effectué avec succès.")
                    InitialiserLiensContacts()
                Else
                    NotifyErreur(results.ErrorMessage)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub
    Protected Sub SupprimerLienContact(cleContact As Integer, typeRelation As String)
        Using svc As New ServiceDossiers.DossiersClient
            Dim params As New ServiceDossiers.ParametresLienDossierEntrepriseContact
            params.Authentication = New ServiceDossiers.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.CleContact = cleContact
            params.CodeDossier = Me.CleEntite
            params.TypeRelation = typeRelation

            Try
                Dim results As ServiceDossiers.OperationResult
                results = svc.SupprimerLienActeur(params)
                If results.OK Then
                    NotifySuccess("Suppression effectuée avec succès.")
                    InitialiserLiensContacts()
                Else
                    NotifyErreur(results.ErrorMessage)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub

    Private Function MettreAJourLieu() As Boolean
        Dim lien As String = ""

        ' Lecture de l'entreprise actuelle
        Using svc As New ServiceEntreprises.EntreprisesClient
            Dim pEntreprise As New ServiceEntreprises.CriteresRechercheEntreprise
            pEntreprise.Authentication = New ServiceEntreprises.AuthenticationParameters
            pEntreprise.Authentication.Token = Tools.GetInstance.getToken
            pEntreprise.DossierLie = Me.CleEntite
            pEntreprise.Type = Me.TypeEntrepriseLieu
            pEntreprise.TypeRelationDossierLie = Me.TypeRelationLieu

            Try
                Dim results As ServiceEntreprises.ResultatRechercheEntreprise = svc.Recherche(pEntreprise)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de charger le lieu lié à l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                    Return False
                ElseIf results.Entreprises.Count > 0 Then
                    lien = results.Entreprises(0).Cle
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
                Return False
            End Try
        End Using

        ' Mise à jour du lien si nécessaire
        If lien.ToUpper <> Me.cmbLieu.SelectedValue.ToUpper Then
            Using svc As New ServiceDossiers.DossiersClient
                Dim pLien As New ServiceDossiers.ParametresLienDossierEntrepriseContact
                pLien.Authentication = New ServiceDossiers.AuthenticationParameters
                pLien.Authentication.Token = Tools.GetInstance.getToken
                pLien.CodeDossier = Me.CleEntite
                pLien.TypeRelation = Me.TypeRelationLieu

                ' Suppression du lien actuel
                If lien <> "" Then
                    pLien.CleEntreprise = lien

                    Try
                        Dim results As ServiceDossiers.OperationResult = svc.SupprimerLienActeur(pLien)
                        If results Is Nothing OrElse Not results.OK Then
                            NotifyErreur("Impossible de supprimer le lien entre le lieu '" & lien & "' et l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                            Return False
                        End If
                    Catch ex As Exception
                        NotifyErreur(ex.Message)
                        Return False
                    End Try
                End If

                ' Ajout du nouveau lien
                If Me.cmbLieu.SelectedValue <> "" Then
                    pLien.CleEntreprise = Me.cmbLieu.SelectedValue

                    Try
                        Dim results As ServiceDossiers.OperationResult = svc.AjouterLienActeur(pLien)
                        If results Is Nothing OrElse Not results.OK Then
                            NotifyErreur("Impossible de créer le lien entre le lieu '" & Me.cmbLieu.SelectedValue & "' et l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                            Return False
                        End If
                    Catch ex As Exception
                        NotifyErreur(ex.Message)
                        Return False
                    End Try
                End If
            End Using
        End If

        Return True
    End Function

    Private Function LireActionDate() As ServiceActions.Action
        Using svc As New ServiceActions.ActionsClient
            Dim params As New ServiceActions.CriteresRechercheAction
            params.Authentication = New ServiceActions.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Type = Me.TypeActionAssemblee
            params.DossierLie = Me.CleEntite

            Try
                Dim results As ServiceActions.ResultatRechercheAction = svc.Recherche(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de charger la date de l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                ElseIf results.Actions.Count > 0 Then
                    Return results.Actions(0)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using

        Return Nothing
    End Function
    Private Function CreerActionDate(ByRef cleAction As Integer) As Boolean
        cleAction = 0

        If Me.dteDateAssemblee.Date <> Tools.DateNull Then
            Using svc As New ServiceActions.ActionsClient
                Dim params As New ServiceActions.ParametresCreationAction
                params.Authentication = New ServiceActions.AuthenticationParameters
                params.Authentication.Token = Tools.GetInstance.getToken
                params.Action = New ServiceActions.Action()
                params.Action.AEffectuerLe = Me.dteDateAssemblee.Date
                params.Action.AEffectuerPar = Me.Master.Utilisateur
                params.Action.DemandeeLe = Now.Date
                params.Action.DemandeePar = Me.Master.Utilisateur
                If Me.tmeHeure.Time <> Tools.DateNull Then
                    params.Action.AEffectuerHeureDebut = Me.tmeHeure.Time
                    params.Action.AEffectuerHeureFin = Me.tmeHeure.Time.AddHours(1)
                End If
                params.Action.Libelle = "Assemblée n°" & Me.CleEntite
                params.Action.Type = Me.TypeActionAssemblee

                Try
                    Dim results As ServiceActions.ResultatCreationAction = svc.Creation(params)
                    If results Is Nothing OrElse Not results.OK Then
                        NotifyErreur("Impossible de créer l'action de l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                        Return False
                    Else
                        cleAction = results.Cle
                    End If
                Catch ex As Exception
                    NotifyErreur(ex.Message)
                    Return False
                End Try
            End Using
        End If

        Return True
    End Function
    Private Function CreerLienActionDate(cleAction As Integer, Optional svc As ServiceDossiers.DossiersClient = Nothing) As Boolean
        Dim disposeSvc As Boolean = False

        If cleAction <> 0 Then
            If svc Is Nothing Then
                disposeSvc = True
                svc = New ServiceDossiers.DossiersClient
            End If

            Dim pDate As New ServiceDossiers.ParametresLienDossierAction
            pDate.Authentication = New ServiceDossiers.AuthenticationParameters
            pDate.Authentication.Token = Tools.GetInstance.getToken
            pDate.CodeDossier = CleEntite
            pDate.CleAction = cleAction

            Try
                Dim results As ServiceDossiers.OperationResult = svc.AjouterLienAction(pDate)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de créer le lien entre l'action n°" & cleAction & " et l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                    Return False
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
                Return False
            End Try

            If disposeSvc Then
                svc.Close()
                svc = Nothing
            End If
        End If

        Return True
    End Function
    Private Function MettreAJourActionDate() As Boolean
        Dim action As ServiceActions.Action = Nothing

        ' Lecture de l'action de la date
        action = LireActionDate()

        If Me.dteDateAssemblee.Date = Tools.DateNull AndAlso action IsNot Nothing Then
            ' Suppression de l'action
            Using svc As New ServiceActions.ActionsClient
                Dim params As New ServiceActions.ParametresSuppressionAction
                params.Authentication = New ServiceActions.AuthenticationParameters
                params.Authentication.Token = Tools.GetInstance.getToken
                params.Cle = action.Cle
                params.SuppressionTotale = True

                Try
                    Dim results As ServiceActions.OperationResult = svc.Suppression(params)
                    If results Is Nothing OrElse Not results.OK Then
                        NotifyErreur("Impossible de supprimer l'action de l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                        Return False
                    End If
                Catch ex As Exception
                    NotifyErreur(ex.Message)
                    Return False
                End Try
            End Using

        ElseIf Me.dteDateAssemblee.Date <> Tools.DateNull Then
            If action Is Nothing Then
                Dim cle As Integer = 0
                ' Création de l'action
                If Not CreerActionDate(cle) Then Return False
                ' Création du lien
                If Not CreerLienActionDate(cle) Then Return False

            ElseIf (action.Effectuee AndAlso (action.EffectueeLe <> Me.dteDateAssemblee.Date Or action.EffectueeHeureDebut <> Me.tmeHeure.Time)) OrElse
                   (Not action.Effectuee AndAlso (action.AEffectuerLe <> Me.dteDateAssemblee.Date Or action.AEffectuerHeureDebut <> Me.tmeHeure.Time)) Then
                ' Mise à jour de l'action
                action.AEffectuerLe = Me.dteDateAssemblee.Date
                If Me.tmeHeure.Time <> Tools.DateNull Then
                    action.AEffectuerHeureDebut = Me.tmeHeure.Time
                    action.AEffectuerHeureFin = Me.tmeHeure.Time.AddHours(1)
                End If
                If action.Effectuee Then
                    action.EffectueeLe = Me.dteDateAssemblee.Date
                    If Me.tmeHeure.Time <> Tools.DateNull Then
                        action.EffectueeHeureDebut = Me.tmeHeure.Time
                        action.EffectueeHeureFin = Me.tmeHeure.Time.AddHours(1)
                    End If
                End If

                Using svc As New ServiceActions.ActionsClient
                    Dim params As New ServiceActions.ParametresCreationAction
                    params.Authentication = New ServiceActions.AuthenticationParameters
                    params.Authentication.Token = Tools.GetInstance.getToken
                    params.Action = action

                    Try
                        Dim results As ServiceActions.OperationResult = svc.MiseAJour(params)
                        If results Is Nothing OrElse Not results.OK Then
                            NotifyErreur("Impossible de mettre à jour l'action de l'assemblée '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                            Return False
                        End If
                    Catch ex As Exception
                        NotifyErreur(ex.Message)
                        Return False
                    End Try
                End Using

            End If
        End If

        Return True
    End Function

End Class